package com.xm.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xm.pojo.Sysuser;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description 后台用户登陆过滤器
 * @Author semstouch
 * @Date 2017/5/6
 **/
@Component("webFilter")
public class WebFilter implements Filter {
    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(WebFilter.class);
    protected FilterConfig filterConfig;


    public void destroy() {//销毁方法
        filterConfig = null;
    }//销毁方法

//    public void destroys(){filterConfig = null;}

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {//主方法
        HttpServletRequest req = (HttpServletRequest) arg0;
        String uri = req.getRequestURI();
        String realUri = uri.replace(req.getContextPath().toString(), "");//对url进行处理
        String accept = req.getHeader("Accept");

        if (isAuth(realUri)) {
            Sysuser sysuser = (Sysuser) req.getSession().getAttribute("sysuser");
            if (sysuser == null) {
                if (accept.contains("application/json")) {//判断是否json请求
                    loginJsonPath(arg0, arg1, arg2);
                } else {
                    loginPath(arg0, arg1, arg2);
                }
            } else {
                commonPath(arg0, arg1, arg2);
            }
        } else {
            commonPath(arg0, arg1, arg2);
        }
    }

//    public void doFilters(ServletRequest arg0, ServletResponse arg1,FilterChain arg2){
//        HttpServletRequest req = (HttpServletRequest) arg0;
//        String uri=req.getRequestURI();
//        String realUri=uri.replace(req.getContextPath().toString(),"");
//        String accept=req.getHeader("Accept");
//        if(isAuth(realUri)){
//            Sysuser sysuser=(Sysuser) req.getSession().getAttribute("sysuser");
//            if (sysuser==null){
//                if (accept.contains("application/json")){
//                    loginJsonPath(arg0,arg1,arg2);
//                }else{
//                    loginPath(arg0,arg1,arg2);
//                }
//            }else{
//                commonPath(arg0,arg1,arg2);
//            }
//        }else{
//            commonPath(arg0,arg1,arg2);
//        }
//    }


    public void loginPath(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {//非json请求
        String loginPath = "/rest/web/toLogin";
        RequestDispatcher loginDispatcher = arg0.getRequestDispatcher(loginPath);//请求容器
        try {
            loginDispatcher.forward(arg0, arg1);
        } catch (ServletException e) {
            logger.error(e.toString());
        } catch (IOException e) {
            logger.error(e.toString());
        }
    }

//    public void loginPaths(ServletRequest arg0,ServletRequest arg1,FilterChain arg2){
//        String loginPath="/rest/web/toLogin";
//        RequestDispatcher loginDispatcher = arg0.getRequestDispatcher(loginPath);
//        try{
//            loginDispatcher.forward(arg0, arg1);
//        }catch(ServletException e){
//            logger.error(e.toString());
//        }catch(IOException e){
//            logger.error(e.toString());
//        }
//    }

    public void loginJsonPath(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {//json请求
        JSONResult jsonResult = new JSONResult();
        jsonResult.setSuccess(false);
        jsonResult.setCode("403");
        jsonResult.setMsg("用户未登录，请重新登陆!");
        ObjectMapper mapper = new ObjectMapper();
        String rs = "";
        try {
            rs = mapper.writeValueAsString(jsonResult);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        arg1.setCharacterEncoding("UTF-8");
        arg1.setContentType("application/json; charset=utf-8");
        try {
            PrintWriter out = arg1.getWriter();
            out.write(rs);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public void loginJsonPaths(ServletRequest arg0,ServletResponse arg1,FilterChain arg2){
//        JSONResult jsonResult = new JSONResult();
//        jsonResult.setSuccess(false);
//        jsonResult.setCode("405");
//        jsonResult.setMsg("用户未登录，请重新登陆！");
//        ObjectMapper mapper = new ObjectMapper();
//        String rs="";
//        try{
//            rs=mapper.writeValueAsString(jsonResult);
//        }catch(Exception e){
//            logger.error(e.toString());
//        }
//        arg1.setCharacterEncoding("UTF-8");
//        arg1.setContentType("applica")
//    }

    /**
     * 判断URL是否需要被过滤
     * 2016-8-2下午7:28:06
     * zhuangjf
     */
    public boolean isAuth(String realUri) {
        boolean noAuth = !realUri.matches("(/rest|rest)/web/toLogin|(/rest|rest)/web/login");//正则表达式url
        return noAuth;
    }

    public void commonPath(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {//常规路径
        try {
            arg2.doFilter(arg0, arg1);
        } catch (IOException e) {
            logger.error(e.toString());
        } catch (ServletException e) {
            logger.error(e.toString());
        }
        return;
    }

    public void init(FilterConfig fConfig) throws ServletException {//初始化方法
        filterConfig = fConfig;
    }
}